package com.chuanyang.driverh.mainstart;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseActivity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.LoginResult;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.ExitAppEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshDriverInfoEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.igexin.sdk.PushManager;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


/**
 * Created by Shinelon on 2016/5/27.
 * 司机的登录页面
 */
public class LoginActivity extends BaseActivity {
    private EditText et_phone;
    private EditText et_password;
    private CheckBox cb_pwd;
    private TextView tv_login_regist;
    private TextView forget_password;
    private TextView login;

    private String phone;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_act_login);
        findView();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void findView() {
        //找到需要操作的控件
        et_phone = (EditText) findViewById(R.id.et_login_phone);
        et_password = (EditText) findViewById(R.id.et_login_password);
        tv_login_regist = (TextView) findViewById(R.id.tv_login_regist);
        forget_password = (TextView) findViewById(R.id.tv_login_forget);
        login = (TextView) findViewById(R.id.tv_login);
        cb_pwd = (CheckBox) findViewById(R.id.cb_pwd);
    }

    private void initData() {
        et_phone.setText(SharedPrefUtil.getPhone());
        et_password.setText(SharedPrefUtil.getPwd());


    }

    private void initListener() {
        //为控件设置点击事件
        login.setOnClickListener(this);
        tv_login_regist.setOnClickListener(this);
        forget_password.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                if (checkInput()) {
                    phone = et_phone.getText().toString().trim();
                    password = et_password.getText().toString().trim();
                    doLogin();
                }
                break;
            case R.id.tv_login_regist:
                ActivityUtil.startActivity(activityContext, new Intent(activityContext, RegisterOrForgetPwdActivity.class).putExtra("type", 1));
                break;
            case R.id.tv_login_forget:
                ActivityUtil.startActivity(activityContext, new Intent(activityContext, RegisterOrForgetPwdActivity.class).putExtra("type", 2));
                break;
        }
    }

    private int times;//登录5次还未解绑成功
    private void doLogin() {
        if (!TextUtils.isEmpty(SharedPrefUtil.getUserId())) {
            boolean bb=false;
            if(ConstUtil.isDebugMode){
                bb=  PushManager.getInstance().unBindAlias(activityContext,"test"+ SharedPrefUtil.getUserId(),true);
            }else{
                bb=   PushManager.getInstance().unBindAlias(activityContext, SharedPrefUtil.getUserId(),true);
            }
            if (!bb && times<5) {
                times++;
                PrintUtil.toast(activityContext,"请稍后再试....");
                return;
            }
        }

        DialogUtil.showLoadingDialog(activityContext, "登录...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", phone);
        params.put("password", password);
        params.put("userType", "2");
        MyHttpUtil.login(activityContext, params, new MyCallback<LoginResult>(activityContext, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(LoginResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    //登录成功返回用户信息
                    if (result.getData() != null) {

                        SharedPrefUtil.clear();//登录成功之后先删除数据。
                        SharedPrefUtil.setFirstUse(false);
                        SharedPrefUtil.setLogined(cb_pwd.isChecked());
                        SharedPrefUtil.setToken(result.getData().getToken());
                        SharedPrefUtil.setUserId(result.getData().getUserId());
                        SharedPrefUtil.setUserName(result.getData().getUsername());
                        SharedPrefUtil.setPhone(phone);
                        SharedPrefUtil.setPwd(cb_pwd.isChecked() ? password : "");

                        String clientId = PushManager.getInstance().getClientid(activityContext);

                        BaseApplication.getInstance().getDriverInfoFromNet();


//                                ActivityUtil.startActivity(activityContext, MainActivityLeader.class);
//                                finish();
                    }
                } else {
                    PrintUtil.toast(activityContext, "用户名或密码错误");
                }
            }
        });
    }

    public void onEventMainThread(RefleshDriverInfoEvent event) {
        if (event.isRefleshDriverInfo()) {
            DriverInfoData driverInfoData = BaseApplication.getInstance().getDriverInfo();
            if (driverInfoData != null && driverInfoData.getFleet() != null && driverInfoData.getFleet().getFleetLeader().equals(driverInfoData.getDriverId())) {
                SharedPrefUtil.setFleetId(driverInfoData.getFleet().getId() + "");
                ActivityUtil.startActivity(activityContext, MainActivityLeader.class);
            } else {
                SharedPrefUtil.setFleetId("");
                ActivityUtil.startActivity(activityContext, MainActivityDriver.class);
            }
            finish();
        }
    }

    private boolean checkInput() {
        String phone = et_phone.getText().toString().trim();
        if (StringUtil.isBlank(phone) || !StringUtil.isPhoneNumber(phone)) {
            PrintUtil.toast(activityContext, "请输入合法的电话号码");
            return false;
        }
        String pwd = et_password.getText().toString();
        if (pwd.length() < 6 || pwd.length() > 20) {
            PrintUtil.toast(activityContext, "请输入6-20位的密码");
            return false;
        }
        return true;
    }

    private long mExitTime;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                PrintUtil.toast(activityContext, "再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                EventBus.getDefault().post(new ExitAppEvent(true, false));
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
